package com.softer.wxzj.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softer.wxzj.common.entity.CommonResult;
import com.softer.wxzj.common.entity.Page;
import com.softer.wxzj.common.enums.*;
import com.softer.wxzj.common.error.CourseException;
import com.softer.wxzj.common.flow.enums.FlowStateEnum;
import com.softer.wxzj.common.flow.enums.FlowTypeEnum;
import com.softer.wxzj.common.flow.util.FlowAddAuditUtil;
import com.softer.wxzj.common.util.*;
import com.softer.wxzj.entity.*;
import com.softer.wxzj.mapper.*;
import com.softer.wxzj.service.ExpProjectReqService;
import com.softer.wxzj.service.ExpSurveyInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Gong Zhiyang
 * @date 2019/7/17
 */
@Service
@Slf4j
public class ExpProjectReqServiceImpl implements ExpProjectReqService {
    @Autowired
    private ExpProjectReqMapper expProjectReqMapper;
    @Autowired
    private OwnerSignatureMapper ownerSignatureMapper;
    @Autowired
    private BaseRegionInfoMapper baseRegionInfoMapper;
    @Autowired
    private ExpSurveyInfoMapper expSurveyInfoMapper;
    @Autowired
    private SysCoreParamMapper syscoreparamMapper;
    @Autowired
    private BaseBuildInfoMapper baseBuildInfoMapper;
    @Autowired
    private BaseCellInfoMapper baseCellInfoMapper;
    @Autowired
    private BaseHouseInfoMapper baseHouseInfoMapper;
    @Autowired
    private FlowAddAuditUtil flowAddAuditUtil;
    @Autowired
    private BaseOrganizationMapper organizationMapper;
    @Autowired
    private ExpPayReqDetailMapper expPayReqDetailMapper;
    @Autowired
    private MaintenanceObjectMapper maintenanceObjectMapper;
    @Autowired
    private ExpPayReqMapper expPayReqMapper;
    @Autowired
    private OperUtil zoneCodeUtil;
    @Autowired
    private ExpSurveyInfoService expSurveyInfoService;
    @Autowired
    private BaseOwnerCommitteeMapper baseOwnerCommitteeMapper;
    @Autowired
    private FileServiceImpl fileService;
    @Autowired
    private BaseSubRegionInfoMapper baseSubRegionInfoMapper;
    @Autowired
    private SysOperatorMapper sysOperatorMapper;

    private final String TWO_HUNDRED_AND_EIGHT = "208";
    private final String TWO_HUNDRED_AND_NINE = "209";
    private final String TWO_HUNDRED_AND_TEN = "210";
    private final String TWO_HUNDRED_AND_ELEVEN = "211";

    /**
     * 获取项目管理列表及总计
     *
     * @param page           分页实体
     * @param baseRegionInfo 查询实体
     * @return 列表
     */
    @Override
    public PageInfo<BaseRegionInfo> getRegionList(Page page, BaseRegionInfo baseRegionInfo) {
        //查询登陆账号的管理区域
        String zoneCode = zoneCodeUtil.getZoneCode();
        baseRegionInfo.setZoneCode(zoneCode);
        BaseRegionInfo currSum = new BaseRegionInfo();
        //分为精确查询和模糊查询
        //总计
        BaseRegionInfo sum = expProjectReqMapper.getSumProject(baseRegionInfo);

        PageHelper.startPage(page.getPageNum(), page.getPageSize());

        //查询列表信息
        List<BaseRegionInfo> list = expProjectReqMapper.getRegionList(baseRegionInfo);
        //当前页项目总计
        int proSum = 0;
        //当前页竣工数总计
        int comSum = 0;
        for (int i = 0; i < list.size(); i++) {
            BaseRegionInfo b = list.get(i);
            proSum += b.getNum();
            comSum += b.getFinishNum();
        }
        currSum.setNum(proSum);
        currSum.setFinishNum(comSum);

        list.add(currSum);
        list.add(sum);

        return  new PageInfo<>(list);
    }

    /**
     * 预览
     *
     * @param page          分页实体
     * @param expProjectReq 查询实体
     * @return 列表
     */
    @Override
    public PageInfo<ExpProjectReq> preview(Page page, ExpProjectReq expProjectReq) {
        String operNo = expProjectReq.getOperNo();
        if (StringUtils.isNotEmpty(operNo)) {
            //查询外网登录的物业企业ID
            SysOperator operator = sysOperatorMapper.getOperInfoByOperNo(operNo);
            if (operator != null) {
                expProjectReq.setOrgReq(operator.getCompanyId());
            }
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        //分为精确查询和模糊查询
        List<ExpProjectReq> list;
        if (StringUtils.isNotEmpty(expProjectReq.getFuzzy())) {
            list = expProjectReqMapper.previewFuzzy(expProjectReq);
        } else {
            list = expProjectReqMapper.preview(expProjectReq);
        }
        //查询未上传图档数量
        list = getFileNum(list);
        return new PageInfo<>(list);
    }

    /**
     * 查询未上传的图档数量
     *
     * @param list 查询的list
     * @return list
     */
    private List<ExpProjectReq> getFileNum(List<ExpProjectReq> list) {
        if (!list.isEmpty()) {
            for (ExpProjectReq expProjectReq : list) {
                String id = expProjectReq.getId();
                //查询拨款管理的未上传的数量
                int payNum = getPayNum(id);
                //查询现场勘察的未上传的数量
                int surveyNum = getSurveyNum(id);
                //查询项目管理未上传的数量
                int projectNum = getProjectNum(id);
                expProjectReq.setUnUploadNum(payNum + surveyNum + projectNum);
                TabAndDeclareEntity tabAndDeclareEntity = whetherAllowDeclaration(expProjectReq);
                expProjectReq.setDeclareFlag(tabAndDeclareEntity.getDeclareFlag());
                expProjectReq.setDeclareMessage(tabAndDeclareEntity.getMessage());
            }
        }
        return list;
    }

    /**
     * 查询项目管理未上传的数量
     *
     * @param id 项目Id
     * @return 未上传的数量
     */
    private int getProjectNum(String id) {
        return expProjectReqMapper.getUnUploadNum(id, FileTypeEnum.USE_PROJECT_APPLY.getType());
    }

    /**
     * 查询现场勘察的未上传的数量
     *
     * @param id 项目Id
     * @return 查询现场勘察的未上传的数量
     */
    private int getSurveyNum(String id) {
        int surveyNum = 0;
        ExpSurveyInfo expSurveyInfo = new ExpSurveyInfo();
        expSurveyInfo.setReqId(id);
        List<ExpSurveyInfo> allList = expSurveyInfoService.getAllList(expSurveyInfo);
        for (ExpSurveyInfo es : allList) {
            int num = expProjectReqMapper.getUnUploadNum(es.getId(), FileTypeEnum.FIELD_INFO.getType());
            surveyNum += num;
        }
        return surveyNum;
    }

    /**
     * 查询拨款管理的未上传的数量
     *
     * @param id 项目Id
     * @return 拨款管理的未上传的数量
     */
    private int getPayNum(String id) {
        return expProjectReqMapper.getUnUploadNum(id, FileTypeEnum.APPROPRIATION_FILE.getType());
    }

    @Override
    public PageInfo<ExpProjectReq> getExpirationDate(Page page, String regionId, String maintainType) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<ExpProjectReq> list = expProjectReqMapper.getExpirationDate(regionId, maintainType);
        return new PageInfo<>(list);
    }

    /**
     * 新增保存
     *
     * @param reqList 维修项目
     * @return 结果
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    @Override
    public CommonResult addSave(ReqList reqList) {
        ExpProjectReq expProjectReq = reqList.getExpProjectReq();
        String buildId = reqList.getNo();
        String uuid = "";
        if (StringUtils.isEmpty(expProjectReq.getId())) {
            expProjectReq.setReqNo(DepositUtil.getNo(NumberEnum.FOUR.getNum().toString()));
            expProjectReq.setCreater(StringUtils.isEmpty(reqList.getOperNo()) ? ShiroUserUtil.getUserName() : reqList.getOperNo());
            uuid = UUIDUtil.getUUID();
            expProjectReq.setId(uuid);
        }
        setParam(expProjectReq);
        if (TWO_HUNDRED_AND_EIGHT.equals(expProjectReq.getMarginType()) || (StringUtils.isNotEmpty(buildId) && TWO_HUNDRED_AND_NINE.equals(expProjectReq.getMarginType()))) {
            ExpProjectReq exp;
            SysCoreParam emptyRoomApportionSysParam = syscoreparamMapper.getInfo("51");
            if (TWO_HUNDRED_AND_EIGHT.equals(expProjectReq.getMarginType())) {
                //若为小区分摊，则新增分摊明细
                exp = expProjectReqMapper.getxqApportionSum(expProjectReq.getRegionId(), emptyRoomApportionSysParam.getParamCode());
            } else {
                Map<String, Object> m = new HashMap<>(3);
                List<String> idList = new ArrayList<>();
                idList.add(buildId);
                //idList
                m.put("list", idList);
                //空房间参与分摊
                m.put("sys", emptyRoomApportionSysParam.getParamCode());
                exp = expProjectReqMapper.getzrApportionSum(m);
            }
            if (exp.getAllArea().compareTo(BigDecimal.ZERO) == 0) {
                return CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "参与分摊房间的总面积为0，无法进行分摊，请维护该小区的房间信息");
            }
            expProjectReq.setAllArea(exp.getAllArea());
            expProjectReq.setAllUser(exp.getAllUser());
            expProjectReq.setPrice(expProjectReq.getBudgSum().divide(expProjectReq.getAllArea(), 2, BigDecimal.ROUND_DOWN));
            expProjectReq.setStep(String.valueOf(NumberEnum.TWO.getNum()));
            //录入业主签名表
            List<OwnerSignature> ol = new ArrayList<>();
            int count = addOwnerSignature(expProjectReq, buildId, ol);
            if (count > 0) {
                String str = "参与分摊的房屋有" + count + "户未做房屋面积维护，请先维护房间面积。";
                return CommonResult.strResult(0, str);
            }
            String message1 = "";
            String message2 = "";
            //房屋变更在途
            int aa = expProjectReqMapper.selectHouseFlowInstance("base_house_info_update", ol);
            if (aa > 0) {
                message1 = "参与分摊的房屋有" + aa + "户在做房屋变更业务，不允许进行分摊划分。";
            }
            //业主变更在途
            int bb = expProjectReqMapper.selectOwnerFlowInstance("base_owner_info_update", ol);
            if (bb > 0) {
                message2 = "参与分摊的房屋有" + bb + "户在做业主变更业务，不允许进行分摊划分。";
            }
            if (aa > 0 || bb > 0) {
                String str = message1 + message2;
                return CommonResult.strResult(0, str);
            }
            dealOwner(ol);
        }
        if (StringUtils.isNotEmpty(expProjectReq.getOrgSupervision())) {
            BaseOrganization info = organizationMapper.getOrgSupervisionInfo(expProjectReq.getOrgSupervision());
            expProjectReq.setSupervisor(info.getContact());
            expProjectReq.setSupervisoryPhone(info.getOrgTel());
        }
        if (StringUtils.isEmpty(uuid)) {
            return CommonResult.ResponseResult(expProjectReqMapper.updateByPrimaryKeySelective(expProjectReq));
        }
        return CommonResult.idResult(expProjectReqMapper.insert(expProjectReq), uuid);
    }

    /**
     * 设置参数
     *
     * @param expProjectReq
     */
    private void setParam(ExpProjectReq expProjectReq) {
        //是否验收（0否，1是）
        expProjectReq.setFinish(NumStrEnum.ZERO.getNum());
        //审核状态（0保存，1审核中，2审核通过，3审核失败，4退回）
        expProjectReq.setFlowState(NumStrEnum.ZERO.getNum());
        //1新建临时保存，2已维护分摊范围，3提交审核，4审核完成，5审核不通过，6部分支付完成，7决算支付完成，8全部支付完成
        expProjectReq.setStep(NumStrEnum.ONE.getNum());
        //状态(0未竣工，1已竣工)
        expProjectReq.setState(NumStrEnum.ZERO.getNum());
        expProjectReq.setAllArea(BigDecimal.ZERO);
        expProjectReq.setAllUser(0);
        expProjectReq.setCalculateBudgSum(BigDecimal.ZERO);
        expProjectReq.setGovernable(BigDecimal.ZERO);
        expProjectReq.setSelfAmount(BigDecimal.ZERO);
        expProjectReq.setSelfSum(0);
        expProjectReq.setPrice(BigDecimal.ZERO);
        expProjectReq.setProreportDate(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
    }

    /**
     * 按小区分摊与维修对象已选定自然幢分摊-录入业主签名信息
     *
     * @param expProjectReq
     */

    public int addOwnerSignature(ExpProjectReq expProjectReq, String buildId, List<OwnerSignature> ol) {
        List<BaseHouseInfo> list;
        SysCoreParam emptyRoomApportionSysParam = syscoreparamMapper.getInfo("51");
        int count;
        if (StringUtils.isNotEmpty(buildId)) {
            //存在固定自然幢的自然幢分摊
            Map<String, Object> m = new HashMap<>(3);
            List<String> idList1 = new ArrayList<>();
            idList1.add(buildId);
            //idList
            m.put("list", idList1);
            //空房间参与分摊
            m.put("sys", emptyRoomApportionSysParam.getParamCode());
            count = expProjectReqMapper.countzrHouseAreaIsNullSum(m);
            if (count == 0) {
                list = expProjectReqMapper.getzrApportionList(m);
                apportion(expProjectReq, ol, list);
            }
        } else {
            //查询当前小区下所有的房屋与业主信息
            count = expProjectReqMapper.countxqHouseAreaIsNullSum(expProjectReq.getRegionId(), emptyRoomApportionSysParam.getParamCode());
            if (count == 0) {
                list = expProjectReqMapper.getxqApportionList(expProjectReq.getRegionId(), emptyRoomApportionSysParam.getParamCode());
                apportion(expProjectReq, ol, list);
            }
        }
        return count;
    }

    private void apportion(ExpProjectReq expProjectReq, List<OwnerSignature> ol, List<BaseHouseInfo> list) {
        //计算预交金额累计
        BigDecimal assiAmountSum = new BigDecimal(0.00);
        for (int i = 0; i < list.size(); i++) {
            BaseHouseInfo h = list.get(i);
            OwnerSignature ownerSignature = new OwnerSignature();
            //预分摊金额
            BigDecimal assiAmount = (expProjectReq.getPrice().multiply(h.getStruArea())).setScale(2, BigDecimal.ROUND_DOWN);
            assiAmountSum = assiAmountSum.add(assiAmount);
            ownerSignature.setAssiAmount(assiAmount);
            setOwnerSignatureParam(ownerSignature, h, expProjectReq);
            ol.add(ownerSignature);
        }
        SysCoreParam sysParam = syscoreparamMapper.getInfo("49");
        if (NumStrEnum.ONE.getNum().equals(sysParam.getParamCode())) {
            //余额不分摊
            expProjectReq.setCalculateBudgSum(assiAmountSum);
        } else {
            //（预算金额 - 实际分摊金额）*100 差价金额转成分 除以总户数   取整取余
            BigDecimal[] bigDecimals = (expProjectReq.getBudgSum().subtract(assiAmountSum)).multiply(new BigDecimal(100)).divideAndRemainder(new BigDecimal(list.size()));
            //整数部分
            if (bigDecimals[0].compareTo(BigDecimal.ZERO) > 0) {
                for (OwnerSignature owner : ol) {
                    BigDecimal a = owner.getAssiAmount().add(bigDecimals[0].divide(new BigDecimal(100)));
                    owner.setAssiAmount(a);
                }
            }
            //余数部分
            if (bigDecimals[1].compareTo(BigDecimal.ZERO) > 0) {
                for (int i = 0; i < bigDecimals[1].intValue(); i++) {
                    OwnerSignature owner1 = ol.get(i);
                    BigDecimal a = owner1.getAssiAmount().add(new BigDecimal(0.01));
                    owner1.setAssiAmount(a);
                }
            }
            expProjectReq.setCalculateBudgSum(expProjectReq.getBudgSum());
        }
        SysCoreParam reservedRatioSwitchSysParam = syscoreparamMapper.getInfo("10");
        //默认：否（业主帐户余额低于续交比例时禁止使用剩余金额）
        String switchSysParam = reservedRatioSwitchSysParam.getParamCode() != null ? reservedRatioSwitchSysParam.getParamCode() : NumStrEnum.ZERO.getNum();
        String ratio = NumStrEnum.ZERO.getNum();
        if (NumStrEnum.ONE.getNum().equals(switchSysParam)) {
            SysCoreParam reservedRatioSysParam = syscoreparamMapper.getInfo(NumStrEnum.SEVEN.getNum());
            //预留比例，默认0.3
            ratio = reservedRatioSysParam.getParamCode() != null ? reservedRatioSysParam.getParamCode() : "0.3";
        }
        dealHouseList(list, ratio, expProjectReq, ol);
    }

    private void setOwnerSignatureParam(OwnerSignature ownerSignature, BaseHouseInfo h, ExpProjectReq expProjectReq) {
        ownerSignature.setOwnerName(h.getOwnerName());
        ownerSignature.setBuildNo(h.getBuildNo());
        BaseBuildInfo build = baseBuildInfoMapper.getInfoById(h.getBuildNo());
        BaseCellInfo cell = baseCellInfoMapper.getInfo(h.getCellNo());
        String houseSite = build.getBuildName() + cell.getCellName() + h.getRoomName();
        ownerSignature.setHouseSite(houseSite);
        ownerSignature.setRoomNo(h.getId());
        ownerSignature.setStruArea(h.getStruArea());
        ownerSignature.setId(UUIDUtil.getUUID());
        ownerSignature.setReqId(expProjectReq.getId());
        ownerSignature.setCreater(ShiroUserUtil.getUserName());
        ownerSignature.setOpinion(NumStrEnum.TWO.getNum());
    }

    private void dealHouseList(List<BaseHouseInfo> list, String ratio, ExpProjectReq expProjectReq, List<OwnerSignature> ol) {
        //自交户数
        int selfSufficientHouseholds = 0;
        //自交金额
        BigDecimal selfPayAmount = BigDecimal.ZERO;
        for (BaseHouseInfo house : list) {
            for (OwnerSignature os : ol) {
                if (house.getId().equals(os.getRoomNo())) {
                    os.setBalance(house.getFundBal());
                    //可用余额=资金本金+本金利息-冻结金额
                    BigDecimal ky = house.getFundBal().add(house.getAccrBal()).subtract(house.getAccountFrozen());
                    //预留金额 = 初交应缴*30%
                    BigDecimal yl = house.getFirstDue().multiply(new BigDecimal(ratio));
                    if (ky.compareTo(yl) > 0) {
                        if (ky.subtract(yl).compareTo(os.getAssiAmount()) > 0) {
                            //系统应交(冻结) = 预算分摊金额
                            os.setGovernable(os.getAssiAmount());
                            //用户自交
                            os.setAssiDept(BigDecimal.ZERO);
                        } else {
                            selfSufficientHouseholds += 1;
                            //系统应交(冻结) = 可用余额 - first_due*30%;
                            os.setGovernable(ky.subtract(yl.setScale(2, BigDecimal.ROUND_DOWN)));
                            //用户自交 = 预算分摊金额 - (可用余额 - first_due*30%);
                            os.setAssiDept(os.getAssiAmount().subtract(os.getGovernable()));

                            selfPayAmount = selfPayAmount.add(os.getAssiDept());
                        }
                    } else {
                        selfSufficientHouseholds += 1;
                        //系统应交
                        os.setGovernable(BigDecimal.ZERO);
                        //用户自交 = 预算分摊金额
                        os.setAssiDept(os.getAssiAmount());
                        selfPayAmount = selfPayAmount.add(os.getAssiDept());
                    }
                }
            }
        }
        expProjectReq.setSelfAmount(selfPayAmount);
        expProjectReq.setGovernable(expProjectReq.getBudgSum().subtract(expProjectReq.getSelfAmount()));
        expProjectReq.setSelfSum(selfSufficientHouseholds);
    }

    /**
     * 分摊明细-录入业主签名信息
     *
     * @param
     */
    @Override
    public Map<String, Object> apportionDetail(List<String> idList, String reqId) {
        ExpProjectReq expProjectReq = expProjectReqMapper.selectByPrimaryKey(reqId);
        Map<String, Object> m = new HashMap<>(5);
        if (StringUtils.isEmpty(expProjectReq.getMarginType())) {
            m.put("error", "分摊类型为空");
            return m;
        }
        //idList
        m.put("list", idList);
        //空房间参与分摊
        SysCoreParam emptyRoomApportionSysParam = syscoreparamMapper.getInfo("51");
        String sys = emptyRoomApportionSysParam.getParamCode() != null ? emptyRoomApportionSysParam.getParamCode() : NumStrEnum.ONE.getNum();
        m.put("sys", sys);
        List<BaseHouseInfo> list;
        ExpProjectReq exp;
        List<OwnerSignature> ol = new ArrayList<>();
        if (idList.size() > 0) {
            if (TWO_HUNDRED_AND_NINE.equals(expProjectReq.getMarginType())) {
                //自然幢
                exp = expProjectReqMapper.getzrApportionSum(m);
                list = expProjectReqMapper.getzrApportionList(m);
            } else if (TWO_HUNDRED_AND_TEN.equals(expProjectReq.getMarginType())) {
                //单元
                exp = expProjectReqMapper.getdyApportionSum(m);
                list = expProjectReqMapper.getdyApportionList(m);
            } else {
                //自定义
                exp = expProjectReqMapper.getzdApportionSum(m);
                list = expProjectReqMapper.getzdApportionList(m);
            }
            expProjectReq.setAllArea(exp.getAllArea());
            expProjectReq.setAllUser(exp.getAllUser());
            if (expProjectReq.getAllArea().compareTo(BigDecimal.ZERO) == 0) {
                m.put("error", "参与分摊房间的总面积为0，无法进行分摊，请维护该小区的房间信息");
                return m;
            }
            //每平米单价
            expProjectReq.setPrice(expProjectReq.getBudgSum().divide(expProjectReq.getAllArea(), 2, BigDecimal.ROUND_DOWN));
            apportion(expProjectReq, ol, list);
        } else {
            expProjectReq.setAllArea(BigDecimal.ZERO);
            expProjectReq.setAllUser(0);
            expProjectReq.setPrice(BigDecimal.ZERO);
            expProjectReq.setCalculateBudgSum(BigDecimal.ZERO);
            expProjectReq.setSelfAmount(BigDecimal.ZERO);
            expProjectReq.setGovernable(BigDecimal.ZERO);
            expProjectReq.setSelfSum(0);
            expProjectReq.setStep(String.valueOf(NumberEnum.ONE.getNum()));
        }
        //所有参与分摊的业主的信息，后续录入exp_project_req_detail
        m.put("ownerSignatureList", ol);
        //分摊的汇总的项目信息，后续录入exp_project_req
        m.put("expProjectReq", expProjectReq);
        return m;
    }

    /**
     * 分摊划分-保存按钮
     *
     * @param expProjectReq 项目详情
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult apportionInfoSave(ExpProjectReq expProjectReq, List<OwnerSignature> ol) {
        String message1 = "";
        String message2 = "";
        //房屋变更在途
        if (ol.size() > 0) {
            int aa = expProjectReqMapper.selectHouseFlowInstance("base_house_info_update", ol);
            if (aa > 0) {
                message1 = "参与分摊的房屋有" + aa + "户在做房屋变更业务，不允许进行分摊划分。";
            }
            //业主变更在途
            int bb = expProjectReqMapper.selectOwnerFlowInstance("base_owner_info_update", ol);
            if (bb > 0) {
                message2 = "参与分摊的房屋有" + bb + "户在做业主变更业务，不允许进行分摊划分。";
            }
            if (aa > 0 || bb > 0) {
                String str = message1 + message2;
                return CommonResult.strResult(0, str);
            }
        }

        List<OwnerSignature> list = ownerSignatureMapper.selectByReqId(expProjectReq.getId());
        if (list.size() > 0) {
            //若之前维护过分摊信息 则房屋的冻结金额应减去之前的系统支付金额
            for (OwnerSignature owner : list) {
                if (owner.getGovernable().compareTo(BigDecimal.ZERO) > 0) {
                    BaseHouseInfo houseInfo = new BaseHouseInfo();
                    houseInfo.setId(owner.getRoomNo());
                    houseInfo.setAccountFrozen(owner.getGovernable().multiply(new BigDecimal(-1)));
                    baseHouseInfoMapper.updatePayAmountById(houseInfo);
                }
            }
        }
        ownerSignatureMapper.deleteByReqId(expProjectReq.getId());
        if (ol.size() > 0) {
            dealOwner(ol);
            expProjectReq.setStep(String.valueOf(NumberEnum.TWO.getNum()));
        }
        expProjectReqMapper.updateByPrimaryKeySelective(expProjectReq);
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    private void dealOwner(List<OwnerSignature> ol) {
        for (OwnerSignature ownerSignature : ol) {
            // 用户实摊金额 即冻结金额 ownerSignature.getGovernable();
            dealOwnerSignatureList(ownerSignature, new BigDecimal(1));
            int num = ownerSignatureMapper.insert(ownerSignature);
            if (num == 0) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }
        }
    }

    /**
     * 修改
     *
     * @param reqList 维修项目
     * @return 结果
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    @Override
    public CommonResult update(ReqList reqList) {
        ExpProjectReq expProjectReq = reqList.getExpProjectReq();
        String buildId = reqList.getNo();
        //old数据
        ExpProjectReq exp = expProjectReqMapper.getInfoById(expProjectReq.getId());
        //查询参与分摊的业主信息
        List<OwnerSignature> list = ownerSignatureMapper.selectByReqId(expProjectReq.getId());
        expProjectReq.setModifier(StringUtils.isEmpty(reqList.getOperNo()) ? ShiroUserUtil.getUserName() : reqList.getOperNo());
        //若step为审核不通过 做项目修改时 应判断step修改到步骤1或者2
        if (exp.getStep().equals(String.valueOf(NumberEnum.FIVE.getNum()))) {
            expProjectReq.setStep(String.valueOf(NumberEnum.ONE.getNum()));
            if (list.size() > 0) {
                expProjectReq.setStep(String.valueOf(NumberEnum.TWO.getNum()));
            }
        }
        boolean a = expProjectReq.getMarginType().equals(exp.getMarginType());
        boolean b = expProjectReq.getMaintainObject().equals(exp.getMaintainObject());
        boolean c = expProjectReq.getBudgSum().compareTo(exp.getBudgSum()) == 0;
        boolean d = expProjectReq.getMaintainType().equals(exp.getMaintainType());
        //重新分摊
        if (!a || !b || !c || !d) {
            if (list.size() > 0) {
                for (OwnerSignature ownerSignature : list) {
                    dealOwnerSignatureList(ownerSignature, new BigDecimal(-1));
                }
            }
            //业主签字删除
            ownerSignatureMapper.deleteByReqId(expProjectReq.getId());
            //拨款管理删除
            expPayReqMapper.delete(expProjectReq.getId());
            //现场勘察删除
            expSurveyInfoMapper.deleteByReqId(expProjectReq.getId());
        } else {
            expProjectReq.setAllUser(exp.getAllUser());
            expProjectReq.setStep(null);
            return CommonResult.ResponseResult(expProjectReqMapper.updateByPrimaryKeySelective(expProjectReq));
        }
        ReqList newReqList = new ReqList();
        newReqList.setExpProjectReq(expProjectReq);
        newReqList.setNo(buildId);
        return addSave(newReqList);
    }

    /**
     * 程序详情
     *
     * @param id ID
     * @return 维修项目
     */
    @Override
    public ExpProjectReq getInfo(String id) {
        ExpProjectReq expProjectReq = expProjectReqMapper.getInfo(id);
        expProjectReq.setFlag(String.valueOf(NumberEnum.ONE.getNum()));
        String regionShare = "小区分摊";
        if (regionShare.equals(expProjectReq.getMarginType())) {
            expProjectReq.setFlag(String.valueOf(NumberEnum.ZERO.getNum()));
        }
        //设置小区名称
        setRegionName(expProjectReq);
        //设置维修类别
        setMaintainTypeName(expProjectReq);
        String maintainObject = expProjectReq.getMaintainObject();
        if (StringUtils.isNotEmpty(maintainObject)) {
            List<MaintenanceEquipment> list = expProjectReqMapper.selectMainEquipmentByIdList(maintainObject);
            if (list.size() > 0) {
                if (StringUtils.isNotEmpty(list.get(0).getBuildId())) {
                    expProjectReq.setFlag(String.valueOf(NumberEnum.ZERO.getNum()));
                }
            }
            expProjectReq.setMaintenanceEquipmentList(list);
            setMaintainObjectName(expProjectReq, list);
        }
        List<BaseOrganization> orgList = new ArrayList<>();
        //施工单位
        dealOrgConstruction(orgList, expProjectReq);
        //监理单位
        dealOrgSupervision(orgList, expProjectReq);
        //审计单位
        dealOrgVerification(orgList, expProjectReq);
        //申请单位
        dealOrgReq(orgList, expProjectReq);
        expProjectReq.setOrgList(orgList);
        //TODO 暂时工程预算 和预算金额相同（预算金额为预算工程费用合计，预算时，监理造价暂时是0）
        expProjectReq.setBudgetAmount(expProjectReq.getBudgSum());
        return expProjectReq;
    }

    /**
     * 设置小区名称
     *
     * @param expProjectReq 项目详情
     */
    public void setRegionName(ExpProjectReq expProjectReq) {
        String regionId = expProjectReq.getRegionId();
        if (StringUtils.isNotEmpty(regionId)) {
            BaseRegionInfo info = baseRegionInfoMapper.getInfo(regionId);
            if (info != null) {
                expProjectReq.setRegionName(info.getRegionName());
            }
        }
    }

    /**
     * 设置维修类别
     *
     * @param expProjectReq 维修项目
     */
    public void setMaintainTypeName(ExpProjectReq expProjectReq) {
        String maintainType = expProjectReq.getMaintainType();
        if (StringUtils.isNotEmpty(maintainType)) {
            MaintenanceObject maintenanceObject = maintenanceObjectMapper.selectByPrimaryKey(maintainType);
            if (maintenanceObject != null) {
                List<String> list = new ArrayList<>(6);
                List<String> nameList = new ArrayList<>(6);
                list.add(maintainType);
                MaintenanceObject mo = maintenanceObjectMapper.selectByPrimaryKey(maintainType);
                nameList.add(mo.getName());
                while (!String.valueOf(NumberEnum.ZERO.getNum()).equals(maintenanceObject.getParentId())) {
                    maintenanceObject = maintenanceObjectMapper.selectByPrimaryKey(maintenanceObject.getParentId());
                    list.add(0, maintenanceObject.getId());
                    nameList.add(0, maintenanceObject.getName());
                }
                String objectId = String.join(",", list);
                String maintainTypeName = String.join("/", nameList);
                expProjectReq.setMaintainType(objectId);
                expProjectReq.setMaintainTypeName(maintainTypeName);
            }
        }
    }

    /**
     * 设置维修对象名称
     *
     * @param expProjectReq 维修项目
     * @param list          维修对象集合
     */
    public void setMaintainObjectName(ExpProjectReq expProjectReq, List<MaintenanceEquipment> list) {
        List<String> collect = list.stream().map(p -> p.getName()).collect(Collectors.toList());
        String join = String.join(",", collect);
        expProjectReq.setMaintainObjectName(join);
    }

    /**
     * 施工单位
     *
     * @param orgList       单位集合
     * @param expProjectReq 项目信息
     */
    private void dealOrgConstruction(List<BaseOrganization> orgList, ExpProjectReq expProjectReq) {
        String oc = expProjectReq.getOrgConstruction();
        if (StringUtils.isNotEmpty(oc)) {
            //施工单位
            BaseOrganization orgConstruction = organizationMapper.getInfo(oc);
            if (orgConstruction != null) {
                orgConstruction.setOrgTypeCode("施工单位");
                orgList.add(orgConstruction);
                expProjectReq.setOrgConstructionName(orgConstruction.getOrgName());
            }
        }
    }

    /**
     * 监理单位
     *
     * @param orgList       单位集合
     * @param expProjectReq 项目信息
     */
    private void dealOrgSupervision(List<BaseOrganization> orgList, ExpProjectReq expProjectReq) {
        String os = expProjectReq.getOrgSupervision();
        if (StringUtils.isNotEmpty(os)) {
            //监理单位
            BaseOrganization orgSupervision = organizationMapper.getInfo(os);
            if (orgSupervision != null) {
                orgSupervision.setOrgTypeCode("监理单位");
                orgList.add(orgSupervision);
            }
        }
    }

    /**
     * 审计单位
     *
     * @param orgList       单位集合
     * @param expProjectReq 项目信息
     */
    private void dealOrgVerification(List<BaseOrganization> orgList, ExpProjectReq expProjectReq) {
        String ov = expProjectReq.getOrgVerification();
        if (StringUtils.isNotEmpty(ov)) {
            //审计单位
            BaseOrganization orgVerification = organizationMapper.getInfo(ov);
            if (orgVerification != null) {
                orgVerification.setOrgTypeCode("审计单位");
                orgList.add(orgVerification);
            }
        }
    }

    /**
     * 申请单位
     *
     * @param orgList       单位集合
     * @param expProjectReq 项目信息
     */
    private void dealOrgReq(List<BaseOrganization> orgList, ExpProjectReq expProjectReq) {
        String orgReq = expProjectReq.getOrgReq();
        if (StringUtils.isNotEmpty(orgReq)) {
            //申请单位
            BaseOrganization bo = organizationMapper.getInfo(orgReq);
            BaseOrganization bo2 = organizationMapper.selectOCInfo(orgReq);
            if (bo != null) {
                bo.setOrgTypeCode("申请单位");
                orgList.add(bo);
                expProjectReq.setOrgReqName(bo.getOrgName());
            }
            if (bo2 != null) {
                bo2.setOrgTypeCode("申请单位");
                orgList.add(bo2);
                expProjectReq.setOrgReqName(bo2.getOrgName());
            }
        }
    }


    /**
     * 分摊划分
     *
     * @param id ID
     * @return 小区下所有的自然幢
     */
    @Override
    public Map<String, List<BaseBuildInfo>> getApportionInfo(String id) {
        //查询项目基本信息
        ExpProjectReq expProjectReq = expProjectReqMapper.selectByPrimaryKey(id);
        String buildId = "";
        String subRegionId = null;
        String maintainObject = expProjectReq.getMaintainObject();
        //查询当前小区下总的Build列表
        List<BaseBuildInfo> totalBuildList = new ArrayList<>();
        if (StringUtils.isNotEmpty(maintainObject)) {
            List<MaintenanceEquipment> list = expProjectReqMapper.selectMainEquipmentByIdList(maintainObject);
            if (list != null && !list.isEmpty()) {
                MaintenanceEquipment maintenanceEquipment = list.get(0);
                if (StringUtils.isNotEmpty(maintenanceEquipment.getBuildId())) {
                    buildId = maintenanceEquipment.getBuildId();
                }
                if (StringUtils.isNotEmpty(maintenanceEquipment.getSubRegionId())) {
                    subRegionId = maintenanceEquipment.getSubRegionId();
                }
            }
        }
        Map<String, List<BaseBuildInfo>> map = new HashMap<>(3);


        //查询当前小区下已选中的Build列表
        List<BaseBuildInfo> selectedBuildList = expProjectReqMapper.getBuildList(expProjectReq.getId());
        if (StringUtils.isNotEmpty(buildId)) {
            BaseBuildInfo baseBuildInfo = baseBuildInfoMapper.getInfoById(buildId);
            if (StringUtils.isNotBlank(baseBuildInfo.getSubRegionNo())) {
                BaseSubRegionInfo baseSubRegionInfo = baseSubRegionInfoMapper.getInfo(baseBuildInfo.getSubRegionNo());
                baseBuildInfo.setBuildName(baseBuildInfo.getBuildName() + "(" + baseSubRegionInfo.getSubRegionName() + ")");
            }
            totalBuildList.add(baseBuildInfo);
        } else {
            List<BaseBuildInfo> baseBuildInfos = baseBuildInfoMapper.getPassBuildList(expProjectReq.getRegionId(), subRegionId);
            for (BaseBuildInfo baseBuildInfo : baseBuildInfos) {
                if (StringUtils.isNotBlank(baseBuildInfo.getSubRegionName())) {
                    baseBuildInfo.setBuildName(baseBuildInfo.getBuildName() + "(" + baseBuildInfo.getSubRegionName() + ")");
                }
                totalBuildList.add(baseBuildInfo);
            }

        }
        //处理当前小区下总的Build列表
        dealTotalBuildList(totalBuildList, selectedBuildList, expProjectReq);
        List<BaseBuildInfo> list = SortUtil.order(totalBuildList);
        map.put("totalBuildlist", list);
        return map;
    }

    /**
     * 处理当前小区下总的Build列表
     *
     * @param selectedBuildList 选中的Build列表
     * @param selectedBuildList 已选中的Build列表
     * @param expProjectReq     项目基本信息
     */
    private void dealTotalBuildList(List<BaseBuildInfo> totalBuildList, List<BaseBuildInfo> selectedBuildList, ExpProjectReq expProjectReq) {
        if (totalBuildList.size() > 0) {
            SysCoreParam emptyRoomApportionSysParam = syscoreparamMapper.getInfo("51");
            for (int i = 0; i < totalBuildList.size(); i++) {
                BaseBuildInfo buildInfo = totalBuildList.get(i);
                BuildSummaryInfo buildSummaryInfo = getBuildSummaryInfo(buildInfo.getId());
                buildInfo.setBuildSummaryInfo(buildSummaryInfo);
                Map<String, Object> xx = new HashMap<>(3);
                List<String> idList = new ArrayList<>();
                idList.add(buildInfo.getId());
                //idList
                xx.put("list", idList);
                //空房间参与分摊
                xx.put("sys", emptyRoomApportionSysParam.getParamCode());
                ExpProjectReq e = expProjectReqMapper.getzrApportionSum(xx);
                //满足分摊条件的所有房间
                buildInfo.setHouseArea(e.getAllArea());
                buildInfo.setHouseQty(e.getAllUser());
                if (e.getAllArea().compareTo(BigDecimal.ZERO) > 0) {
                    int count = expProjectReqMapper.countzrHouseAreaIsNullSum(xx);
                    if (count > 0) {
                        buildInfo.setMessage("参与分摊的房屋有" + count + "户未做房屋面积维护，请先维护房间面积。");
                    }
                } else {
                    buildInfo.setMessage("该自然幢下参与分摊的房间总面积为0，请先维护房间面积。");
                }
                //未选
                buildInfo.setRemark(NumStrEnum.ZERO.getNum());
                dealSelectBuildList(selectedBuildList, buildInfo, expProjectReq);
            }
        }
    }

    /**
     * 处理当前小区下已选中的Build列表
     *
     * @param selectedBuildList 选中的Build列表
     * @param buildInfo         自然幢信息
     * @param expProjectReq     项目基本信息
     */
    private void dealSelectBuildList(List<BaseBuildInfo> selectedBuildList, BaseBuildInfo buildInfo, ExpProjectReq expProjectReq) {
        Map<String, String> mcell = new HashMap<>(10);
        if (selectedBuildList.size() > 0) {
            for (int j = 0; j < selectedBuildList.size(); j++) {
                BaseBuildInfo selectedBuild = selectedBuildList.get(j);
                if (buildInfo.getId().equals(selectedBuild.getId())) {
                    //全选
                    buildInfo.setRemark(NumStrEnum.ONE.getNum());
                    if (TWO_HUNDRED_AND_TEN.equals(expProjectReq.getMarginType()) || TWO_HUNDRED_AND_ELEVEN.equals(expProjectReq.getMarginType())) {
                        //按单元分摊
                        mcell.put("reqId", expProjectReq.getId());
                        mcell.put("buildNo", selectedBuild.getId());
                        List<String> cellList = expProjectReqMapper.getCellList(mcell);
                        buildInfo.setCellList(cellList);
                        List<String> houseList = expProjectReqMapper.getHouseList(mcell);
                        buildInfo.setHouseList(houseList);
                        //查询当前自然幢下总的房间数
                        int totalSum = buildInfo.getHouseQty();
                        //查询当前自然幢下已选中的房间个数
                        int selectedSum = houseList.size();
                        //部分选中
                        buildInfo.setRemark(NumStrEnum.TWO.getNum());
                        if (totalSum == selectedSum) {
                            //全选
                            buildInfo.setRemark(NumStrEnum.ONE.getNum());
                        }
                    }
                }
            }
        }
    }

    /**
     * 刪除
     *
     * @param id ID
     * @return 結果
     */
    @Override
    public CommonResult delete(String id) {
        List<OwnerSignature> list = ownerSignatureMapper.selectByReqId(id);

        if (list.size() > 0) {
            for (OwnerSignature ownerSignature : list) {
                dealOwnerSignatureList(ownerSignature, new BigDecimal(-1));
            }
        }
        //业主签字删除
        ownerSignatureMapper.deleteByReqId(id);
        //拨款管理删除
        expPayReqMapper.delete(id);
        //有质保金时拨款批次表删除
        expPayReqDetailMapper.deleteByReqId(id);
        //现场勘察删除
        expSurveyInfoMapper.deleteByReqId(id);
        return CommonResult.ResponseResult(expProjectReqMapper.deleteByPrimaryKey(id));
    }

    private void dealOwnerSignatureList(OwnerSignature ownerSignature, BigDecimal flag) {
        if (ownerSignature.getGovernable().compareTo(BigDecimal.ZERO) > 0) {
            BaseHouseInfo h = new BaseHouseInfo();
            h.setId(ownerSignature.getRoomNo());
            h.setAccountFrozen(ownerSignature.getGovernable().multiply(flag));
            baseHouseInfoMapper.updatePayAmountById(h);
        }
    }

    /**
     * 竣工验收列表
     *
     * @param page          分页实体
     * @param expProjectReq 查询实体
     * @return 列表
     */
    @Override
    public PageInfo<ExpProjectReq> finish(Page page, ExpProjectReq expProjectReq) {
        //分为精确查询和模糊查询
        String zoneCode = zoneCodeUtil.getZoneCode();
        expProjectReq.setZoneCode(zoneCode);
        List<ExpProjectReq> list;
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        if (StringUtils.isNotEmpty(expProjectReq.getFuzzy())) {
            list = expProjectReqMapper.finishFuzzy(expProjectReq.getFuzzy(), zoneCode);
        } else {
            list = expProjectReqMapper.finish(expProjectReq);
        }

        for (ExpProjectReq exp : list) {
            boolean finishCancel = true;
            exp.setFinishCancel(finishCancel);
            buttonFlag(exp, finishCancel);
        }
        return new PageInfo<>(list);
    }

    /**
     * 验收是否可以取消按钮展示
     *
     * @param exp 项目实体
     * @return
     */
    private void buttonFlag(ExpProjectReq exp, boolean finishCancel) {
        if ("是".equals(exp.getFinish()) || NumStrEnum.ONE.getNum().equals(exp.getFinish())) {
            finishCancel = true;
            exp.setFinishCancel(finishCancel);
            List<ExpPayReq> expPayReqList = expPayReqMapper.getExpPayReqByReqIdAndIsFinalPay(exp.getId(), NumStrEnum.ONE.getNum());
            if (expPayReqList.isEmpty()) {
                //置灰
                finishCancel = false;
                exp.setFinishCancel(finishCancel);
                exp.setMessage("未维护拨款管理");
                return;
            }
            if (Integer.parseInt(expPayReqList.get(0).getFlowState()) == 1 || Integer.parseInt(expPayReqList.get(0).getFlowState()) == NumberEnum.TWO.getNum()) {
                //置灰
                finishCancel = false;
                exp.setFinishCancel(finishCancel);
                exp.setMessage("决算金额已参与拨款使用，无法撤销验收");
                return;
            }
            int minNum = expPayReqMapper.minNum(exp.getId());
            if (minNum == 1) {
                //置灰
                finishCancel = false;
                exp.setFinishCancel(finishCancel);
                exp.setMessage("决算金额已参与拨款使用，无法撤销验收");
                return;
            }
            if (minNum != 0) {
                ExpPayReq expPayReq = expPayReqMapper.getLastSumById(exp.getId(), (minNum - 1));
                if (Integer.parseInt(expPayReq.getFlowState()) == 1 || Integer.parseInt(expPayReq.getFlowState()) == NumberEnum.TWO.getNum()) {
                    //置灰
                    finishCancel = false;
                    exp.setFinishCancel(finishCancel);
                    exp.setMessage("决算金额已参与拨款使用，无法撤销验收");
                    return;
                }
            }
        }
    }

    /**
     * 验收详情查询
     *
     * @param id      项目id
     * @param arcType 图档大类
     * @return
     */
    @Override
    public ExpProjectReq getFinishInfo(String id, String arcType) {
        ExpProjectReq expProjectReq = getInfo(id);
        ExpProjectReq hz = expProjectReqMapper.getFinishInfo(id);
        expProjectReq.setAmountPaid(hz.getAmountPaid());
        expProjectReq.setAppliedAmount(hz.getAppliedAmount());
        expProjectReq.setBudgSumPayProportion(hz.getBudgSumPayProportion());
        expProjectReq.setBudgSumPayBal(hz.getBudgSumPayBal());
        expProjectReq.setLastRate(hz.getLastRate());
        boolean finishCancel = false;
        expProjectReq.setFinishCancel(finishCancel);
        buttonFlag(expProjectReq, finishCancel);
        // 查询图档信息
        List<FileVO> fileVOList = fileService.getFileVOList(id, arcType);
        expProjectReq.setFileTypeList(fileVOList);
        return expProjectReq;
    }

    /**
     * 验收撤销
     *
     * @param id      项目id
     * @param arcType 图档大类
     * @param operNo  外网操作账号
     * @return 撤销结果
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult finishCancel(String id, String arcType, String operNo) {
        ExpProjectReq exp = expProjectReqMapper.getInfoById(id);
        ExpProjectReq expProjectReq = new ExpProjectReq();
        expProjectReq.setId(id);
        expProjectReq.setModifier(StringUtils.isEmpty(operNo) ? ShiroUserUtil.getUserName() : operNo);
        //未验收
        expProjectReq.setFinish(NumStrEnum.ZERO.getNum());
        expProjectReq.setState(NumStrEnum.ZERO.getNum());
        expProjectReq.setFinishSelfNum(0);
        //房屋冻结金额修改
        List<OwnerSignature> list = ownerSignatureMapper.selectByReqId(id);
        dealOwnerSignature(list);
        //拨款金额修改,拨付金额累计
        BigDecimal payAmountSum = BigDecimal.ZERO;
        List<ExpPayReq> expPayReqList = expPayReqMapper.getList(id);
        if (expPayReqList.size() > 0) {
            //calculateBudgSum计算的预算金额
            BigDecimal calculateBudgSum = exp.getCalculateBudgSum();
            for (ExpPayReq expPayReq : expPayReqList) {
                expPayReq.setPayAmount((calculateBudgSum.multiply(expPayReq.getPayRate()).multiply(new BigDecimal(0.01))).setScale(2, BigDecimal.ROUND_DOWN));
                payAmountSum = payAmountSum.add(expPayReq.getPayAmount());
            }
            dealPay(payAmountSum, calculateBudgSum, expPayReqList, exp);
            for (ExpPayReq e : expPayReqList) {
                expPayReqMapper.updateByPrimaryKey(e);
            }
            if (exp.getIsLast() == 1) {
                //有质保金
                int size = expPayReqList.size() - 1;
                ExpPayReq expPayReq = expPayReqList.get(size);
                BigDecimal deptMoney = BigDecimal.ZERO;
                BigDecimal ableOrShare = BigDecimal.ZERO;
                List<ExpPayReqDetail> payReqDetailList = new ArrayList<>();
                islastSumApportion(false, list, deptMoney, ableOrShare, expPayReq, payReqDetailList, expProjectReq, exp);
                //录入表pay_req_detail
                int num = addPayReqDetail(payReqDetailList);
                if (num <= 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                }
            }
        }
        int i = expProjectReqMapper.finishCancel(expProjectReq);
        if (i <= 0) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        //撤销验收后，将验收图片删除
        int num = fileService.deleteByArcType(id, arcType);
        if (num == 0) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "验收图片删除失败");
        }
        return CommonResult.ResponseResult(i);
    }

    public void dealPay(BigDecimal payAmountSum, BigDecimal calculateBudgSum, List<ExpPayReq> expPayReqList, ExpProjectReq exp) {
        if (payAmountSum.compareTo(calculateBudgSum) != 0) {
            //倒数第二次的计算
            for (int i = 0; i < expPayReqList.size(); i++) {
                ExpPayReq expPayReq = expPayReqList.get(i);
                if (exp.getIsLast() == 1) {
                    //是否质保金 0否 1 是
                    if ((expPayReq.getReqNum()) == (exp.getPayCount() - 1)) {
                        //倒数第二次的计算 不按比例计算
                        //倒数第二次拨款金额
                        expPayReq.setPayAmount(calculateBudgSum.subtract(payAmountSum.subtract(expPayReq.getPayAmount())));
                    }
                } else {
                    //非质保金
                    if (expPayReq.getReqNum() == exp.getPayCount()) {
                        //最后一次拨款
                        expPayReq.setPayAmount(calculateBudgSum.subtract(payAmountSum.subtract(expPayReq.getPayAmount())));
                    }
                }
            }
        }
    }

    /**
     * 房屋冻结金额修改
     *
     * @param list
     */
    private void dealOwnerSignature(List<OwnerSignature> list) {
        for (OwnerSignature ownerSignature : list) {
            if (ownerSignature.getGovernable().compareTo(new BigDecimal(0.00)) > 0 || ownerSignature.getActualGovernable().compareTo(new BigDecimal(0.00)) > 0) {
                BaseHouseInfo h = new BaseHouseInfo();
                h.setId(ownerSignature.getRoomNo());
                BigDecimal accountFrozen = (ownerSignature.getActualGovernable().subtract(ownerSignature.getGovernable())).multiply(new BigDecimal(-1));
                h.setAccountFrozen(accountFrozen);
                baseHouseInfoMapper.updatePayAmountById(h);
            }
        }
    }

    /**
     * 录入表pay_req_detail
     *
     * @param payReqDetailList
     * @return
     */
    private int addPayReqDetail(List<ExpPayReqDetail> payReqDetailList) {
        for (ExpPayReqDetail e : payReqDetailList) {
            int num = expPayReqDetailMapper.updateByPrimaryKey(e);
            if (num <= 0) {
                return 0;
            }
        }
        return 1;
    }

    /**
     * 质保金分摊
     */
    private void islastSumApportion(boolean isFinalPay, List<OwnerSignature> list, BigDecimal deptMoney, BigDecimal ableOrShare, ExpPayReq expPayReq, List<ExpPayReqDetail> payReqDetailList, ExpProjectReq expProjectReq, ExpProjectReq exp) {
        for (int i = 0; i < list.size(); i++) {
            //业主已拨付总金额
            ExpPayReqDetail expPayReqDetailSum = expPayReqDetailMapper.getSumByReqId(list.get(i).getReqId(), list.get(i).getRoomNo());
            ExpPayReqDetail expPayReqDetail = expPayReqDetailMapper.getInfoByPayReqIdAndHouseId(expPayReq.getId(), list.get(i).getRoomNo());
            grantApplySubElse(isFinalPay, deptMoney, ableOrShare, list.get(i), expPayReq, expPayReqDetail, expPayReqDetailSum, expProjectReq);
            payReqDetailList.add(expPayReqDetail);
            deptMoney = expPayReqDetail.getDeptMoney();
            ableOrShare = expPayReqDetail.getAbleOrShare();
        }
        if ((ableOrShare.add(deptMoney)).compareTo(expPayReq.getPayAmount()) != 0) {
            BigDecimal[] bigDecimals = (expPayReq.getPayAmount().subtract(ableOrShare.add(deptMoney))).multiply(new BigDecimal(100)).divideAndRemainder(new BigDecimal(list.size()));
            //整数部分
            if (bigDecimals[0].compareTo(BigDecimal.ZERO) > 0) {
                for (ExpPayReqDetail expPayReqDetail : payReqDetailList) {
                    BigDecimal money = expProjectReqMapper.getSumByReqId(expPayReqDetail) != null ? expProjectReqMapper.getSumByReqId(expPayReqDetail) : BigDecimal.ZERO;

                    //数据库已拨付总金额
                    for (int i = 0; i < list.size(); i++) {
                        if (expPayReqDetail.getHouseId() == list.get(i).getRoomNo()) {
                            if (exp.getIsLast() == 1) {
                                ExpPayReq p = expPayReqMapper.getLastSumById(exp.getId(), exp.getPayCount());
                                ExpPayReqDetail pd = expPayReqDetailMapper.getInfoByPayReqIdAndHouseId(p.getId(), list.get(i).getRoomNo());
                                //当有质保金拨款时，数据库该用户已拨付总金额-预存的质保金金额
                                money = money.subtract(pd.getMoney());
                            }
                            //可支配金额
                            BigDecimal governable;
                            if (isFinalPay) {
                                governable = list.get(i).getActualGovernable();
                            } else {
                                governable = list.get(i).getGovernable();
                            }
                            //用户已拨付总金额 < 可支配余额
                            if (money.compareTo(governable) < 0) {
                                BigDecimal a = expPayReqDetail.getMoney().add(bigDecimals[0].divide(new BigDecimal(100)));
                                expPayReqDetail.setMoney(a);
                            } else {
                                BigDecimal a = expPayReqDetail.getSelfAmount().add(bigDecimals[0].divide(new BigDecimal(100)));
                                expPayReqDetail.setSelfAmount(a);
                            }
                        }
                    }
                }
            }
            //余数部分
            if (bigDecimals[1].compareTo(BigDecimal.ZERO) > 0) {
                for (int i = 0; i < bigDecimals[1].intValue(); i++) {
                    ExpPayReqDetail expPayReqDetail1 = payReqDetailList.get(i);
                    BigDecimal money = expProjectReqMapper.getSumByReqId(expPayReqDetail1) != null ? expProjectReqMapper.getSumByReqId(expPayReqDetail1) : BigDecimal.ZERO;

                    //数据库已拨付总金额
                    for (int j = 0; j < list.size(); j++) {
                        if (expPayReqDetail1.getHouseId().equals(list.get(j).getRoomNo())) {
                            //可支配金额
                            BigDecimal governable;
                            if (isFinalPay) {
                                governable = list.get(j).getActualGovernable();
                            } else {
                                governable = list.get(j).getGovernable();
                            }
                            //当拨付总金额=数据库已拨付总金额+此次拨款金额 < 可支配余额
                            if (money.add(expPayReqDetail1.getMoney()).compareTo(governable) < 0) {
                                BigDecimal a = expPayReqDetail1.getMoney().add(new BigDecimal(0.01));
                                expPayReqDetail1.setMoney(a);
                            } else {
                                BigDecimal a = expPayReqDetail1.getSelfAmount().add(new BigDecimal(0.01));
                                expPayReqDetail1.setSelfAmount(a);
                            }

                        }
                    }
                }
            }
        }
    }

    /**
     * 验收时，输入决算金额最大上限
     *
     * @param id 项目id
     * @return
     */
    @Override
    public BigDecimal inputFinishNumMax(String id) {
        ExpProjectReq exp = expProjectReqMapper.getInfoById(id);
        SysCoreParam sysParam = syscoreparamMapper.getInfo("53");
        //决算金额不能超过预算的比例
        String param = sysParam.getParamCode() != null ? sysParam.getParamCode() : "0.1";
        BigDecimal inputFinishNumMax = exp.getBudgSum().add(exp.getBudgSum().multiply(new BigDecimal(param)));
        return inputFinishNumMax;
    }

    /**
     * 验收保存
     *
     * @param expProjectReq 项目实体
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult updateFinish(ExpProjectReq expProjectReq) {
        ExpProjectReq exp = expProjectReqMapper.getInfoById(expProjectReq.getId());
        BigDecimal validAmount = expProjectReq.getAppliedAmount();
        if (exp.getIsLast() == null) {
            return CommonResult.ResponseResult(0, "未维护项目的拨款管理");
        }
        if (exp.getIsLast() == 1) {
            //有质保金 则 决算金额 > 已申请金额 + 决算质保金金额
            ExpPayReq isLastPayReq = expPayReqMapper.getLastSumById(exp.getId(), exp.getPayCount());
            BigDecimal isLastPayAmount = expProjectReq.getInputFinalSum().multiply(isLastPayReq.getPayRate()).multiply(new BigDecimal(0.01)).setScale(2, BigDecimal.ROUND_DOWN);
            validAmount = expProjectReq.getAppliedAmount().add(isLastPayAmount);
        }
        if (validAmount.compareTo(expProjectReq.getInputFinalSum()) > 0) {
            String str = "决算金额应大于 " + validAmount + " (元)";
            return CommonResult.strResult(0, str);
        }
        //已验收
        expProjectReq.setFinish(NumStrEnum.ONE.getNum());
        //决算单价
        expProjectReq.setFinalPrice(expProjectReq.getInputFinalSum().divide(exp.getAllArea(), 2, BigDecimal.ROUND_DOWN));
        expProjectReq.setState(NumStrEnum.ONE.getNum());
        //余额是否参与分摊
        SysCoreParam sysParam = syscoreparamMapper.getInfo("49");

        List<OwnerSignature> ol = new ArrayList<>();
        //自交户数
        int finishSelfSufficientHouseholds = 0;
        //自交金额
        BigDecimal finishSelfPayAmount = BigDecimal.ZERO;
        //累计决算金额
        BigDecimal actualAmountSum = new BigDecimal(0.00);
        List<OwnerSignature> list = ownerSignatureMapper.selectByReqId(exp.getId());
        for (int i = 0; i < list.size(); i++) {
            OwnerSignature ownerSignature = list.get(i);
            //决算分摊金额
            BigDecimal actualAmount = (expProjectReq.getFinalPrice().multiply(ownerSignature.getStruArea())).setScale(2, BigDecimal.ROUND_DOWN);
            actualAmountSum = actualAmountSum.add(actualAmount);
            ownerSignature.setActualAmount(actualAmount);
            ol.add(ownerSignature);
        }
        if (String.valueOf(NumberEnum.ONE.getNum()).equals(sysParam.getParamCode())) {
            //余额不分摊
            expProjectReq.setFinalSum(actualAmountSum);
        } else {
            //余额参与分摊
            //（决算金额 - 实际分摊金额）*100 差价金额转成分 /总户数   取整取余
            BigDecimal[] bigDecimals = (expProjectReq.getInputFinalSum().subtract(actualAmountSum)).multiply(new BigDecimal(100)).divideAndRemainder(new BigDecimal(list.size()));
            //整数部分
            if (bigDecimals[0].compareTo(BigDecimal.ZERO) > 0) {
                for (OwnerSignature owner : ol) {
                    BigDecimal a = owner.getActualAmount().add(bigDecimals[0].divide(new BigDecimal(100)));
                    owner.setActualAmount(a);
                }
            }
            //余数部分
            if (bigDecimals[1].compareTo(BigDecimal.ZERO) > 0) {
                for (int i = 0; i < bigDecimals[1].intValue(); i++) {
                    OwnerSignature owner1 = ol.get(i);
                    BigDecimal a = owner1.getActualAmount().add(new BigDecimal(0.01));
                    owner1.setActualAmount(a);
                }
            }
            expProjectReq.setFinalSum(expProjectReq.getInputFinalSum());
        }
        SysCoreParam reservedRatioSwitchSysParam = syscoreparamMapper.getInfo("10");
        //默认：否（业主帐户余额低于续交比例时禁止使用剩余金额）
        String switchSysParam = reservedRatioSwitchSysParam.getParamCode() != null ? reservedRatioSwitchSysParam.getParamCode() : NumStrEnum.ZERO.getNum();
        String ratio = NumStrEnum.ZERO.getNum();
        if (String.valueOf(NumberEnum.ONE.getNum()).equals(switchSysParam)) {
            SysCoreParam reservedRatioSysParam = syscoreparamMapper.getInfo(NumStrEnum.SEVEN.getNum());
            //预留比例，默认0.3
            ratio = reservedRatioSysParam.getParamCode() != null ? reservedRatioSysParam.getParamCode() : "0.3";
        }
        updateOwnerAndHouse(ol, ratio, finishSelfSufficientHouseholds, finishSelfPayAmount, expProjectReq);
        //判断是否做过拨款管理，若做过 则需维护pay_req表的拨付金额字段（pay_amount）
        dealPay(expProjectReq, exp, ol);
        int num = expProjectReqMapper.updateFinish(expProjectReq);
        if (num <= 0) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
//        //TODO 修改维修对象的保修到期日
//        exp.setWarrantyExpirationDate(expProjectReq.getWarrantyExpirationDate());
//        String maintainObject = exp.getMaintainObject();
//        if (StringUtils.isNotEmpty(maintainObject)){
//        }
        //处理图片修改
        CommonResult result = fileService.updateFile(expProjectReq.getFileTypeList(), expProjectReq.getId());
        if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), result.getMessage());
        }
        return CommonResult.ResponseResult(num);
    }

    /**
     * 判断是否做过拨款管理，若做过 则需维护pay_req表的拨付金额字段（pay_amount）
     *
     * @param expProjectReq 传输的项目
     * @param exp           查询数据库的项目
     * @param ol            业主集合
     */
    private void dealPay(ExpProjectReq expProjectReq, ExpProjectReq exp, List<OwnerSignature> ol) {
        List<ExpPayReq> payReqList = expPayReqMapper.getList(expProjectReq.getId());
        BigDecimal amountSum = BigDecimal.ZERO;
        BigDecimal budgAmountSum = BigDecimal.ZERO;
        if (payReqList.size() > 0) {
            BigDecimal isLastSum = BigDecimal.ZERO;
            int payReqListSize = payReqList.size();
            if (exp.getIsLast() == 1) {
                //是否质保金 0否 1 是
                isLastSum = expProjectReq.getFinalSum().multiply(payReqList.get(payReqList.size() - 1).getPayRate()).multiply(new BigDecimal(0.01)).setScale(2, BigDecimal.ROUND_DOWN);
                payReqListSize = payReqList.size() - 1;

                payReqList.get(payReqList.size() - 1).setPayAmount(isLastSum);
                amountSum = amountSum.add(isLastSum);
            }
            for (int k = 0; k < payReqListSize; k++) {
                ExpPayReq expPayReq = payReqList.get(k);
                if (expPayReq.getIsFinalPay().equals(NumStrEnum.ZERO.getNum())) {
                    budgAmountSum = budgAmountSum.add(expPayReq.getPayAmount());
                }
            }
            budgAmountSum = budgAmountSum.add(isLastSum);
            if (budgAmountSum.compareTo(expProjectReq.getFinalSum()) > 0) {
                boolean flag = true;
                for (int t = 0; t < payReqListSize; t++) {
                    ExpPayReq expPayReq = payReqList.get(t);
                    if (flag) {
                        if ((amountSum.add(expPayReq.getPayAmount())).compareTo(expProjectReq.getFinalSum()) >= 0) {
                            flag = false;
                            expPayReq.setPayAmount(expProjectReq.getFinalSum().subtract(amountSum));
                        }
                    } else {
                        expPayReq.setPayAmount(BigDecimal.ZERO);
                    }
                    amountSum = amountSum.add(expPayReq.getPayAmount());
                }
            } else {
                boolean flag = true;
                for (int i = 0; i < payReqListSize; i++) {
                    ExpPayReq expPayReq = payReqList.get(i);
                    if (flag) {
                        if (expPayReq.getIsFinalPay().equals(NumStrEnum.ONE.getNum())) {
                            expPayReq.setPayAmount(expProjectReq.getFinalSum().multiply(expPayReq.getPayRate()).multiply(new BigDecimal(0.01)).setScale(2, BigDecimal.ROUND_DOWN));
                        }
                        if ((amountSum.add(expPayReq.getPayAmount())).compareTo(expProjectReq.getFinalSum()) > 0) {
                            flag = false;
                            expPayReq.setPayAmount(expProjectReq.getFinalSum().subtract(amountSum));
                        }
                    } else {
                        expPayReq.setPayAmount(BigDecimal.ZERO);
                    }
                    amountSum = amountSum.add(expPayReq.getPayAmount());
                }
            }
            if (amountSum.compareTo(expProjectReq.getFinalSum()) != 0) {
                //倒数第二次的计算
                for (int i = 0; i < payReqList.size(); i++) {
                    ExpPayReq expPayReq = payReqList.get(i);
                    if (exp.getIsLast() == 1) {
                        //是否质保金 0否 1 是
                        if ((expPayReq.getReqNum()) == (exp.getPayCount() - 1)) {
                            //倒数第二次的计算 不按比例计算 ，倒数第二次拨款金额
                            expPayReq.setPayAmount(expProjectReq.getFinalSum().subtract(amountSum.subtract(expPayReq.getPayAmount())));
                        }
                    } else {
                        //非质保金
                        if (expPayReq.getReqNum() == exp.getPayCount()) {
                            //最后一次拨款
                            expPayReq.setPayAmount(expProjectReq.getFinalSum().subtract(amountSum.subtract(expPayReq.getPayAmount())));
                        }
                    }
                }
            }
            for (ExpPayReq e : payReqList) {
                expPayReqMapper.updateByPrimaryKey(e);
            }
            dealLastPay(expProjectReq, exp, payReqList, ol);
        }
    }

    /**
     * 处理质保金
     *
     * @param expProjectReq 传输的项目实体
     * @param exp           查询的项目实体
     * @param payReqList    拨款集合
     * @param ol            业主集合
     */
    private void dealLastPay(ExpProjectReq expProjectReq, ExpProjectReq exp, List<ExpPayReq> payReqList, List<OwnerSignature> ol) {
        if (exp.getIsLast() == 1) {
            //有质保金
            int size = payReqList.size() - 1;
            ExpPayReq expPayReq = payReqList.get(size);
            BigDecimal deptMoney = BigDecimal.ZERO;
            BigDecimal ableOrShare = BigDecimal.ZERO;
            List<ExpPayReqDetail> payReqDetailList = new ArrayList<>();
            islastSumApportion(true, ol, deptMoney, ableOrShare, expPayReq, payReqDetailList, expProjectReq, exp);
            //录入表pay_req_detail
            for (ExpPayReqDetail e : payReqDetailList) {
                expPayReqDetailMapper.updateByPrimaryKey(e);
            }
        }
    }

    private void updateOwnerAndHouse(List<OwnerSignature> ol, String ratio, int finishSelfSufficientHouseholds, BigDecimal finishSelfPayAmount, ExpProjectReq expProjectReq) {
        for (OwnerSignature os : ol) {
            BaseHouseInfo house = baseHouseInfoMapper.getInfo(os.getRoomNo());
            BigDecimal accrBal = house.getAccrBal() != null ? house.getAccrBal() : BigDecimal.ZERO;
            BigDecimal fundBal = house.getFundBal() != null ? house.getFundBal() : BigDecimal.ZERO;
            BigDecimal accountFrozen = house.getAccountFrozen() != null ? house.getAccountFrozen() : BigDecimal.ZERO;
            BigDecimal firstDue = house.getFirstDue() != null ? house.getFirstDue() : BigDecimal.ZERO;
            ExpPayReqDetail pay = new ExpPayReqDetail();
            pay.setPayReqId(os.getReqId());
            pay.setHouseId(os.getRoomNo());
            //可用余额 = 资金本金 + 本金利息 - 冻结金额 + 预算可支配金额
            BigDecimal ky = fundBal.add(accrBal).subtract(accountFrozen).add(os.getGovernable());
            //账户预留金额：初交应缴的30%
            BigDecimal yl = firstDue.multiply(new BigDecimal(ratio));
            if (ky.compareTo(yl) > 0) {
                //实际可支配余额 = ky - yl
                if ((ky.subtract(yl)).compareTo(os.getActualAmount()) > 0) {
                    //决算系统应交(冻结) = 决算分摊金额
                    os.setActualGovernable(os.getActualAmount());
                    //决算用户自交
                    os.setActualDept(BigDecimal.ZERO);
                } else {
                    finishSelfSufficientHouseholds += 1;
                    //决算系统应交(冻结) = 可用余额 - first_due*30%;
                    os.setActualGovernable(ky.subtract(yl.setScale(2, BigDecimal.ROUND_DOWN)));
                    //用户自交 = 决算分摊金额 - (可用余额 - first_due*30%);
                    os.setActualDept(os.getActualAmount().subtract(os.getActualGovernable()));

                    finishSelfPayAmount = finishSelfPayAmount.add(os.getActualDept());
                }
            } else {
                finishSelfSufficientHouseholds += 1;
                //决算系统应交
                os.setActualGovernable(BigDecimal.ZERO);
                //决算用户自交 = 决算分摊金额
                os.setActualDept(os.getActualAmount());

                finishSelfPayAmount = finishSelfPayAmount.add(os.getActualDept());
            }
            //入业主表
            ownerSignatureMapper.updateByPrimaryKeySelective(os);
            //入房屋表
            if (os.getGovernable().compareTo(new BigDecimal(0.00)) > 0) {
                BaseHouseInfo h = new BaseHouseInfo();
                h.setId(os.getRoomNo());
                h.setAccountFrozen(os.getActualGovernable().subtract(os.getGovernable()));
                baseHouseInfoMapper.updatePayAmountById(h);
            }
        }
        expProjectReq.setFinishSelfAmount(finishSelfPayAmount.setScale(2, BigDecimal.ROUND_DOWN));
        expProjectReq.setFinishSelfNum(finishSelfSufficientHouseholds);
    }

    private void grantApplySubElse(boolean isFinalPay, BigDecimal deptMoney, BigDecimal ableOrShare, OwnerSignature expProjectReqDetail, ExpPayReq expPayReq, ExpPayReqDetail expPayReqDetail, ExpPayReqDetail expPayReqDetailSum, ExpProjectReq expProjectReq) {

        BigDecimal moneySum = expPayReqDetailSum != null ? expPayReqDetailSum.getMoney() : BigDecimal.ZERO;
        int deptMoneyCont;//欠款金额对比用
        int ableOrShareCont;//可用金额或决算分摊金额对比用
        BigDecimal amount;//应交总金额
        BigDecimal governable;//可用总金额
        if (isFinalPay) {
            amount = expProjectReqDetail.getActualAmount();
            governable = expProjectReqDetail.getActualGovernable();
            deptMoneyCont = expProjectReqDetail.getActualDept().compareTo(BigDecimal.ZERO);
            ableOrShareCont = expProjectReqDetail.getActualGovernable().compareTo(BigDecimal.ZERO);
        } else {
            amount = expProjectReqDetail.getAssiAmount();
            governable = expProjectReqDetail.getGovernable();
            deptMoneyCont = expProjectReqDetail.getAssiDept().compareTo(BigDecimal.ZERO);
            ableOrShareCont = expProjectReqDetail.getGovernable().compareTo(BigDecimal.ZERO);
        }
        if (deptMoneyCont > 0 && ableOrShareCont == 0) {
            //全部用户自缴
            expPayReqDetail.setMoney(BigDecimal.ZERO);
            expPayReqDetail.setSelfAmount(amount.multiply(expPayReq.getPayRate()).multiply(new BigDecimal(0.01)).setScale(2, BigDecimal.ROUND_DOWN));

            deptMoney = deptMoney.add(expPayReqDetail.getSelfAmount());

        } else if (deptMoneyCont == 0 && ableOrShareCont > 0) {
            //全部系统支付
            expPayReqDetail.setSelfAmount(BigDecimal.ZERO);
            expPayReqDetail.setMoney(amount.multiply(expPayReq.getPayRate()).multiply(new BigDecimal(0.01)).setScale(2, BigDecimal.ROUND_DOWN));
            ableOrShare = ableOrShare.add(expPayReqDetail.getMoney());

        } else if (deptMoneyCont > 0 && ableOrShareCont > 0) {
            //本次拨款业主应交金额
            BigDecimal money = (amount.multiply(expPayReq.getPayRate()).multiply(new BigDecimal(0.01)).setScale(2, BigDecimal.ROUND_DOWN));
            // 预留质保金
            //还有剩余可支配余额 = 系统应交 - 已拨付金额(包含质保金)

            BigDecimal ky = governable.subtract(moneySum.subtract(expPayReqDetail.getMoney()));
            if (ky.compareTo(BigDecimal.ZERO) > 0) {
                int moneyNum = money.compareTo(ky);
                if (moneyNum <= 0) {
                    //剩余可支配余额比此次拨款金额大
                    expPayReqDetail.setSelfAmount(BigDecimal.ZERO);
                    expPayReqDetail.setMoney(money);
                    ableOrShare = ableOrShare.add(expPayReqDetail.getMoney());
                } else {
                    expPayReqDetail.setSelfAmount(money.subtract(ky));
                    expPayReqDetail.setMoney(ky);
                    ableOrShare = ableOrShare.add(expPayReqDetail.getMoney());
                    deptMoney = deptMoney.add(expPayReqDetail.getSelfAmount());
                }
            } else {
                //全部用户自缴
                expPayReqDetail.setSelfAmount(money);
                expPayReqDetail.setMoney(BigDecimal.ZERO);
                deptMoney = deptMoney.add(expPayReqDetail.getSelfAmount());
            }
        }
        expPayReqDetail.setDeptMoney(deptMoney);
        expPayReqDetail.setAbleOrShare(ableOrShare);
    }

    /**
     * 是否允许申报
     *
     * @param expProjectReq 项目实体
     * @return 能否申报、能否展示标志
     */
    @Override
    public TabAndDeclareEntity whetherAllowDeclaration(ExpProjectReq expProjectReq) {
        Boolean surveyFlag = true;
        Boolean surveyIcon = false;
        boolean flag = false;
        TabAndDeclareEntity td;
        //判断是否需要现场勘察
        List<ExpSurveyInfo> list = expSurveyInfoMapper.seleteByReqId(expProjectReq.getId());
        SysCoreParam surveySysParam = syscoreparamMapper.getInfo("29");
        if (surveySysParam.getParamCode().equals(NumStrEnum.ONE.getNum())) {
            surveyFlag = false;
            flag = true;
            td = whetherOwnerSignature(expProjectReq, flag);
        } else if (surveySysParam.getParamCode().equals(NumStrEnum.TWO.getNum())) {
            flag = true;
            surveyIcon = true;
            td = whetherOwnerSignature(expProjectReq, flag);
        } else {
            if (list.size() > 0) {
                flag = true;
                surveyIcon = true;
            }
            td = whetherOwnerSignature(expProjectReq, flag);
        }
        td.setSurveyFlag(surveyFlag);
        td.setSurveyIcon(surveyIcon);
        td.setSurveyNum(list != null ? list.size() : 0);
        //查询项目管理未上传的数量
        int projectNum = getProjectNum(expProjectReq.getId());
        td.setProjectNum(projectNum);
        //返回值待定
        return td;
    }

    /**
     * 业主签名
     *
     * @param expProjectReq 维修项目信息
     * @param flag          现场勘察划分标志
     * @return 能否申报、能否展示标志
     */
    private TabAndDeclareEntity whetherOwnerSignature(ExpProjectReq expProjectReq, boolean flag) {
        Boolean finishFlag = false;
        Boolean finishIcon = false;
        Boolean payFlag = false;
        Boolean declareFlag = false;
        Boolean ownerSignatureFlag = true;
        Boolean ownerSignatureIcon = false;
        int allPayNum = 0;
        int accKeepPayNum = 0;
        TabAndDeclareEntity td = new TabAndDeclareEntity();
        //判断是否需要业主签字
        ExpProjectReq pro = expProjectReqMapper.selectByPrimaryKey(expProjectReq.getId());
        if (NumStrEnum.ONE.getNum().equals(pro.getFinish())) {
            finishIcon = true;
        }
        if (NumStrEnum.TWO.getNum().equals(pro.getFlowState()) && !NumStrEnum.NINE.getNum().equals(pro.getStep())) {
            finishFlag = true;
            List<ExpPayReq> list = expPayReqMapper.getList(expProjectReq.getId());
            if (list != null && !list.isEmpty()) {
                //项目审核通过，并且已经维护了拨款批次，则tab页允许点击
                payFlag = true;
                allPayNum = list.size();
                //查询已经银行记账的批次数量
                accKeepPayNum = expPayReqMapper.getAccKeepPayNum(expProjectReq.getId());
            }
        }
        SysCoreParam sysParam3 = syscoreparamMapper.getInfo("32");
        if (NumStrEnum.ONE.getNum().equals(sysParam3.getParamCode())) {
            ownerSignatureFlag = false;
            if (flag) {
                declareFlag = true;
            }
        } else if (NumStrEnum.TWO.getNum().equals(sysParam3.getParamCode())) {
            if (flag) {
                declareFlag = true;
            }
        } else {
            //项目id
            List<OwnerSignature> list = ownerSignatureMapper.selectByReqId(expProjectReq.getId());
            if (list.size() > 0) {
                //需要业主签字，超过2/3才可以申报
                int opinionY = 0;
                BigDecimal allAreaY = new BigDecimal(0.00);
                for (int i = 0; i < list.size(); i++) {
                    OwnerSignature ownerSignature = list.get(i);
                    //同意
                    if (NumStrEnum.ZERO.getNum().equals(ownerSignature.getOpinion())) {
                        opinionY += 1;
                        allAreaY = allAreaY.add(ownerSignature.getStruArea());
                    }
                }
                //放弃(默认为不同意),业主签字户数超过2/3
                int a = new BigDecimal(opinionY).divide(new BigDecimal((list.size())), 2, BigDecimal.ROUND_DOWN).compareTo(new BigDecimal(2).divide(new BigDecimal(3), 2, BigDecimal.ROUND_DOWN));
                if (pro.getAllArea().compareTo(BigDecimal.ZERO) > 0) {
                    //业主签字的总面积超过2/3
                    int b = (allAreaY.divide(pro.getAllArea(), 2, BigDecimal.ROUND_DOWN)).compareTo(new BigDecimal(2).divide(new BigDecimal(3), 2, BigDecimal.ROUND_DOWN));
                    if (a > 0 && b > 0) {
                        ownerSignatureIcon = true;
                        if (flag) {
                            declareFlag = true;
                        }
                    }
                }
            }
        }
        if (NumStrEnum.TWO.getNum().equals(pro.getProjectType())) {
            //如果是应急项目，没有业主签名
            declareFlag = true;
        }
        if (!flag) {
            declareFlag = false;
            td.setMessage("未维护现场勘察信息");
        }
        if (flag && !declareFlag && (NumStrEnum.THREE.getNum().equals(sysParam3.getParamCode()))) {
            td.setMessage("业主同意户数或业主同意户数的总面积，未超过总分摊的2/3");
        }
        if (NumStrEnum.ONE.getNum().equals(pro.getFlowState()) || NumStrEnum.TWO.getNum().equals(pro.getFlowState())) {
            declareFlag = false;
            td.setMessage("项目申请已提交");
        }
        CommonResult result = fileService.checkFile(expProjectReq.getId(), "use_project_apply");
        if (ShiroResultEnum.FAIL.getCode() == result.getData()) {
            declareFlag = false;
            td.setMessage(result.getMessage());
        }
        td.setDeclareFlag(declareFlag);
        td.setOwerSignatureFlag(ownerSignatureFlag);
        td.setFinishFlag(finishFlag);
        td.setFinishIcon(finishIcon);
        td.setPayFlag(payFlag);
        td.setAllPayNum(allPayNum);
        td.setAccKeepNum(accKeepPayNum);
        td.setOwnerSignatureIcon(ownerSignatureIcon);
        return td;
    }

    /**
     * 申报
     *
     * @param id 项目ID
     * @return 修改结果
     */
    @Override
    public CommonResult updateState(String id, String proReportUser) {
        ExpProjectReq expProjectReq = expProjectReqMapper.getInfoById(id);
        expProjectReq.setProreportDate(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now()));
        expProjectReq.setStep(String.valueOf(NumberEnum.THREE.getNum()));
        //判断项目是否需要申报(0否，1是) 若不需要 则项目状态直接审核完成
        SysCoreParam sysParam = syscoreparamMapper.getInfo("27");
        if (String.valueOf(NumberEnum.ZERO.getNum()).equals(sysParam.getParamCode())) {
            //审核通过
            expProjectReq.setFlowState(String.valueOf(NumberEnum.TWO.getNum()));
            expProjectReq.setStep(String.valueOf(NumberEnum.FOUR.getNum()));
        } else {
            //审核中
            expProjectReq.setFlowState(String.valueOf(NumberEnum.ONE.getNum()));
            // 绑定审批流，应急使用（内网提交，走内网应急使用流程；外网提交，查询是否存在业委会，若存在，走业委会流程，不存在，走居委会流程），一般使用（内外网都走一般流程）
            String initState;
            if (NumStrEnum.TWO.getNum().equals(expProjectReq.getProjectType())) {
                //应急使用（内网提交，走内网应急使用流程；外网提交，查询是否存在业委会，若存在，走业委会流程，不存在，走居委会流程）
                if (StringUtils.isEmpty(proReportUser)) {
                    //内网提交，走内网应急使用流程
                    initState = flowAddAuditUtil.initFlow(id, FlowTypeEnum.INTRANET_EMERGENCY.getType(), null);
                } else {
                    //外网提交，查询是否存在业委会，若存在，走业委会流程，不存在，走居委会流程
                    String committee = expProjectReqMapper.getCommittee(expProjectReq.getRegionId());
                    if (StringUtils.isEmpty(committee)) {
                        //不存在，走居委会流程
                        initState = flowAddAuditUtil.initFlow(id, FlowTypeEnum.NEIGHBORHOOD_COMMITTEE_EMERGENCY.getType(), null);
                    } else {
                        initState = flowAddAuditUtil.initFlow(id, FlowTypeEnum.INDUSTRY_COMMITTEE_EMERGENCY.getType(), null);
                    }
                }
            } else {
                initState = flowAddAuditUtil.initFlow(id, FlowTypeEnum.PROJECT_REQ.getType(), null);
            }
            if (initState == null) {
                CommonResult.ResponseResult(NumberEnum.ZERO.getNum(), "项目[" + expProjectReq.getReqName() + "]已申请，请勿重复提交");
            }
            //当返回通过NumStrEnum.TWO.getNum()时 表明该记录不需要审核，直接更新到业务表
            if (FlowStateEnum.PASS.getState().equals(initState)) {
                //审核通过
                expProjectReq.setFlowState(String.valueOf(NumberEnum.TWO.getNum()));
                expProjectReq.setStep(String.valueOf(NumberEnum.FOUR.getNum()));
            }
        }
        //项目申报人与申报时间
        if (StringUtils.isEmpty(proReportUser)) {
            proReportUser = ShiroUserUtil.getUser().getOperName();
        } else {
            //查询外网登录的物业企业ID
            SysOperator operator = sysOperatorMapper.getOperInfoByOperNo(proReportUser);
            proReportUser = operator.getOperName();
        }
        expProjectReq.setProreportUser(proReportUser);
        return CommonResult.ResponseResult(expProjectReqMapper.audit(expProjectReq));
    }


    /**
     * 预分摊清册&决算清册
     *
     * @param reqId 项目id
     */
    @Override
    public PageInfo<OwnerSignature> apportionForm(String reqId, Page page) {
        //totalSum总计
        OwnerSignature totalSum = ownerSignatureMapper.selectByReqIdSum(reqId);
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<OwnerSignature> ownerSignatureList = ownerSignatureMapper.selectByReqId(reqId);
        BigDecimal allSa = new BigDecimal(0.00), allFbAab = new BigDecimal(0.00);
        BigDecimal allAa = new BigDecimal(0.00), allG = new BigDecimal(0.00);
        BigDecimal allAd = new BigDecimal(0.00), allAca = new BigDecimal(0.00);
        BigDecimal allAcg = new BigDecimal(0.00), allAcd = new BigDecimal(0.00);
        //currentSum当前页总计
        OwnerSignature currentSum = new OwnerSignature();
        for (OwnerSignature os : ownerSignatureList) {
            allSa = allSa.add(os.getStruArea());
            allFbAab = allFbAab.add(os.getFundBalAndAccrBal());
            //预算
            allAa = allAa.add(os.getAssiAmount());
            allG = allG.add(os.getGovernable());
            allAd = allAd.add(os.getAssiDept());
            //决算
            allAca = allAca.add(os.getActualAmount());
            allAcg = allAcg.add(os.getActualGovernable());
            allAcd = allAcd.add(os.getActualDept());

        }
        currentSum.setStruArea(allSa);
        currentSum.setFundBalAndAccrBal(allFbAab);
        //预算
        currentSum.setAssiAmount(allAa);
        currentSum.setGovernable(allG);
        currentSum.setAssiDept(allAd);
        //决算
        currentSum.setActualAmount(allAca);
        currentSum.setActualGovernable(allAcg);
        currentSum.setActualDept(allAcd);

        ownerSignatureList.add(currentSum);
        ownerSignatureList.add(totalSum);
        return new PageInfo<>(ownerSignatureList);
    }

    @Override
    public ExpProjectReq getInfoById(String id) {
        return expProjectReqMapper.getInfoById(id);
    }

    /**
     * 批量申报
     *
     * @param list 项目Id集合
     * @return 修改结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult batchCommit(List<String> list) {
        for (String id : list) {
            CommonResult commonResult = updateState(id, "");
            if (ShiroResultEnum.FAIL.getCode() == commonResult.getData()) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), commonResult.getMessage());
            }
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    /**
     * 查询自然幢汇总信息，用于分摊划分时的自然幢浮窗显示
     *
     * @param id 自然幢Id
     * @return 汇总信息
     */
    @Override
    public BuildSummaryInfo getBuildSummaryInfo(String id) {
        return expProjectReqMapper.getBuildSummaryInfo(id);
    }

    /**
     * 获取使用申请表数据信息
     *
     * @param id 项目ID
     * @return 申请表数据
     */
    @Override
    public Application getApplication(String id) {
        Application application = new Application();
        //查询项目信息
        ExpProjectReq info = expProjectReqMapper.selectByPrimaryKey(id);
        if (info != null) {
            application.setReqName(info.getReqName());
            application.setAllUser(info.getAllUser());
            application.setAllArea(info.getAllArea());
            //施工单位信息
            BaseOrganization bo = organizationMapper.getInfo(info.getOrgConstruction());
            if (bo != null) {
                application.setOrgConstruction(bo.getOrgName());
            }
            application.setBudgetAmount(info.getBudgSum());
            application.setTotalCost(info.getBudgSum());
            //获取申请人信息
            BaseOrganization baseOrganization = getOrganization(info.getOrgType(), info.getOrgReq());
            application.setApplicant(baseOrganization.getOrgName());
            application.setCertNo(baseOrganization.getOrgCertificate());
            application.setAddress(baseOrganization.getAddress());
            application.setCertType(baseOrganization.getOrgBirefName());
        }
        //查询有关签名信息
        OwnerSignature ownerSignature = ownerSignatureMapper.getSum(id);
        if (ownerSignature != null) {
            application.setAgreeArea(ownerSignature.getTysum());
            application.setAgreeUser(ownerSignature.getTynum());
            application.setAreaRatio(ownerSignature.getAreaRatio());
            application.setOwnerRatio(ownerSignature.getOwnerRatio());
        }
        return application;
    }

    @Override
    public PageInfo<ExpProjectReq> selectByHouseId(Page page, ExpProjectReq expProjectReq) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<ExpProjectReq> list = expProjectReqMapper.selectByHouseId(expProjectReq);
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<ExpProjectReq> selectByMainObject(Page page, ExpProjectReq expProjectReq) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<ExpProjectReq> ExpProjectReq = expProjectReqMapper.selectByMainObject(expProjectReq);
        return new PageInfo<>(ExpProjectReq);
    }

    /**
     * 通过维修企业、审计企业、监理企业查询维修项目的接口
     *
     * @param page          分页实体
     * @param expProjectReq 查询实体
     * @return 维修项目列表
     */
    @Override
    public PageInfo<ExpProjectReq> getProjectReqListByCorpId(Page page, ExpProjectReq expProjectReq) {
        String type = expProjectReq.getType();
        List<ExpProjectReq> list = new ArrayList<>();
        if (StringUtils.isEmpty(type)) {
        } else if (!NumStrEnum.ONE.getNum().equals(type) && !NumStrEnum.TWO.getNum().equals(type) && !NumStrEnum.THREE.getNum().equals(type)) {
        } else {
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
            list = expProjectReqMapper.getProjectReqListByConstruction(expProjectReq);
        }
        return new PageInfo<>(list);
    }

    /**
     * 查询自然幢维修记录列表
     *
     * @param page    分页实体
     * @param buildId 自然幢ID
     * @return 列表
     */
    @Override
    public PageInfo<ExpProjectReq> getBuildProjectList(Page page, String buildId) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<ExpProjectReq> list = expProjectReqMapper.getBuildProjectList(buildId);
        //查询未上传图档数量
        list = getFileNum(list);
        return new PageInfo<>(list);
    }

    /**
     * 外网批量申报
     *
     * @param reqList list 项目Id集合
     *                operNo 登录账号
     * @return 修改结果
     */
    @Override
    public CommonResult batchCommitFromExtraNet(ReqList reqList) {
        List<String> list = reqList.getList();
        if (list != null && !list.isEmpty()) {
            for (String id : list) {
                CommonResult commonResult = updateState(id, reqList.getOperNo());
                if (ShiroResultEnum.FAIL.getCode() == commonResult.getData()) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), commonResult.getMessage());
                }
            }
        }
        return CommonResult.ResponseResult(NumberEnum.ONE.getNum());
    }

    /**
     * 查詢详情
     * 用于跳转连接的查询
     *
     * @param id ID
     * @return 维修项目
     */
    @Override
    public ExpProjectReq getDetails(String id) {
        ExpProjectReq expProjectReq = expProjectReqMapper.getDetails(id);
        setRegionName(expProjectReq);
        String maintainObject = expProjectReq.getMaintainObject();
        if (StringUtils.isNotEmpty(maintainObject)) {
            List<MaintenanceEquipment> list = expProjectReqMapper.selectMainEquipmentByIdList(maintainObject);
            setMaintainObjectName(expProjectReq, list);
        }
        List<BaseOrganization> orgList = new ArrayList<>();
        //申请单位
        dealOrgReq(orgList, expProjectReq);
        //施工单位
        dealOrgConstruction(orgList, expProjectReq);
        setMaintainTypeName(expProjectReq);
        return expProjectReq;
    }

    /**
     * 获取申请人信息
     *
     * @param orgReq  申请单位ID
     * @param orgType 申请人类型（1物业企业；2业委会居委会；3个人）
     * @return 申请人信息
     */
    private BaseOrganization getOrganization(String orgType, String orgReq) {
        if (StringUtils.isNotEmpty(orgType)) {
            switch (orgType) {
                case "1":
                    BaseOrganization base = organizationMapper.getInfo(orgReq);
                    base.setOrgBirefName("社会信用代码");
                    return organizationMapper.getInfo(orgReq);
                case "2":
                    BaseOwnerCommittee info = baseOwnerCommitteeMapper.getInfo(orgReq);
                    BaseOrganization baseOrganization = new BaseOrganization();
                    baseOrganization.setOrgName(info.getOwnerCommitteeName());
                    baseOrganization.setOrgCertificate(info.getOrgCertificate());
                    baseOrganization.setAddress(info.getAddress());
                    baseOrganization.setOrgBirefName("社会信用代码");
                    return baseOrganization;
                default:
                    //TODO 其他情况待定
            }
        }
        return new BaseOrganization();
    }

    /**
     * 查询当前小区选中的维修类别下的维修对象信息
     *
     * @param maintenanceEquipment regionId            小区id&
     *                             maintenanceObjectId 对象类别ID
     *                             subRegionId 分区ID
     *                             buildId 自然幢ID
     *                             splitRange 分摊范围
     * @return 维修对象信息
     */
    @Override
    public List<MaintenanceEquipment> selectMaintenanceEquipment(MaintenanceEquipment maintenanceEquipment) {
        return expProjectReqMapper.selectMaintenanceEquipment(maintenanceEquipment);
    }

    /**
     * 项目审核查询列表
     *
     * @param page
     * @param expProjectReq
     * @return
     */
    @Override
    public PageInfo<ExpProjectReq> projectCheckList(Page page, ExpProjectReq expProjectReq, String operNo) {
        //根据operNo查询companyId
        SysOperator sysOperator = sysOperatorMapper.selectName(operNo);
        List<ExpProjectReq> list = new ArrayList<>();
        if (sysOperator != null && !RoleCodeEnum.ZERO_FIVE.getType().equals(sysOperator.getCompanyNo()) && !RoleCodeEnum.ZERO_SIX.getType().equals(sysOperator.getCompanyNo())) {
            expProjectReq.setOrgReq(sysOperator.getCompanyId());
            expProjectReq.setOperNo(operNo);
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
            list = expProjectReqMapper.projectCheckList(expProjectReq);
        }
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<ExpProjectReq> appropriationCheckList(Page page, ExpProjectReq expProjectReq) {
        //根据operNo查询companyId
        SysOperator sysOperator = sysOperatorMapper.selectName(expProjectReq.getOperNo());
        List<ExpProjectReq> list = new ArrayList<>();
        if (sysOperator != null && !RoleCodeEnum.ZERO_FIVE.getType().equals(sysOperator.getCompanyNo()) && !RoleCodeEnum.ZERO_SIX.getType().equals(sysOperator.getCompanyNo())) {
            expProjectReq.setOrgReq(sysOperator.getCompanyId());
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
            list = expProjectReqMapper.appropriationCheckList(expProjectReq);
        }
        return new PageInfo<>(list);
    }

    /**
     * 分摊划分重置
     *
     * @param reqId 项目ID
     * @return 分摊划分重置结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult reset(String reqId) {
        //查询当前项目状态
        ExpProjectReq projectReq = expProjectReqMapper.getInfoById(reqId);
        if (!NumStrEnum.TWO.getNum().equals(projectReq.getStep())) {
            return CommonResult.ResponseResult(0, "项目状态已发生改变，禁止重置");
        }
        //业主签字删除
        ownerSignatureMapper.deleteByReqId(reqId);
        //拨款管理删除
        expPayReqMapper.delete(reqId);
        //将状态改为新建临时保存
        int num = expProjectReqMapper.changeStep(reqId, "1");
        return CommonResult.ResponseResult(num);
    }

    /**
     * 业委会/居委会项目审核查询列表
     *
     * @param page          分页实体
     * @param expProjectReq 查询实体
     * @return 项目审核查询列表
     */
    @Override
    public PageInfo<ExpProjectReq> projectCheckListForCommittee(Page page, ExpProjectReq expProjectReq) {
        //根据operNo查询companyId
        SysOperator sysOperator = sysOperatorMapper.selectName(expProjectReq.getOperNo());
        List<ExpProjectReq> list = new ArrayList<>();
        if (sysOperator != null) {
            if (RoleCodeEnum.ZERO_FIVE.getType().equals(sysOperator.getCompanyNo()) || RoleCodeEnum.ZERO_SIX.getType().equals(sysOperator.getCompanyNo())) {
                expProjectReq.setOrgReq(sysOperator.getCompanyId());
                PageHelper.startPage(page.getPageNum(), page.getPageSize());
                list = expProjectReqMapper.projectCheckListForCommittee(expProjectReq);
            }
        }
        return new PageInfo<>(list);
    }

    /**
     * 业委会/居委会拨款审核查询列表
     *
     * @param page          分页实体
     * @param expProjectReq 查询实体
     * @return 拨款审核查询列表
     */
    @Override
    public PageInfo<ExpProjectReq> appropriationCheckListForCommittee(Page page, ExpProjectReq expProjectReq) {
        //根据operNo查询companyId
        SysOperator sysOperator = sysOperatorMapper.selectName(expProjectReq.getOperNo());
        List<ExpProjectReq> list = new ArrayList<>();
        if (sysOperator != null) {
            if (RoleCodeEnum.ZERO_FIVE.getType().equals(sysOperator.getCompanyNo()) || RoleCodeEnum.ZERO_SIX.getType().equals(sysOperator.getCompanyNo())) {
                expProjectReq.setOrgReq(sysOperator.getCompanyId());
                PageHelper.startPage(page.getPageNum(), page.getPageSize());
                list = expProjectReqMapper.appropriationCheckListForCommittee(expProjectReq);
            }
        }
        return new PageInfo<>(list);
    }

    /**
     * 业委会/居委会维修项目管理列表
     *
     * @param page          分页实体
     * @param expProjectReq 查询实体
     * @return 列表
     */
    @Override
    public PageInfo<ExpProjectReq> previewForCommittee(Page page, ExpProjectReq expProjectReq) {
        //查询业委会/居委会登录账号信息
        SysOperator operator = sysOperatorMapper.getOperInfoByOperNo(expProjectReq.getOperNo());
        List<ExpProjectReq> list = new ArrayList<>();
        if (operator != null) {
            if (RoleCodeEnum.ZERO_FIVE.getType().equals(operator.getCompanyNo()) || RoleCodeEnum.ZERO_SIX.getType().equals(operator.getCompanyNo())) {
                expProjectReq.setOrgReq(operator.getCompanyId());
                PageHelper.startPage(page.getPageNum(), page.getPageSize());
                list = expProjectReqMapper.previewForCommittee(expProjectReq);
            }
        }
        //查询未上传图档数量
        list = getFileNum(list);
        return new PageInfo<>(list);
    }

}
